<?php


namespace apps\marriage\core\service;


use apps\marriage\core\logic\FileLogic;
use apps\marriage\core\model\MemberImages;
use think\Exception;
use vm\com\BaseModel;
use vm\com\BaseService;

class MemberImagesService extends BaseService
{

    /**
     * @return MemberImages
     */
    protected function getModel()
    {
        return new MemberImages();
    }

    /**
     * @return FileLogic
     */
    private function getFileLogic()
    {
        return logic('File', LOGIC_NAMESPACE);
    }

    /**
     * @return MemberProfileService
     */
    private function getMemberProfileService()
    {
        return service('MemberProfile', SERVICE_NAMESPACE);
    }

    public function create(array $data)
    {
        $member = $this->getMemberProfileService()->getByUserId($data['user_id']);
        if($member['realname_auth_status'] == 0) {
            throw new Exception('请先完成实名认证');
        }
        $rights = $this->getMemberProfileService()->getVipRightsByUserId($data['user_id']);
        if($rights['album_photo_pics'] != -1 && $this->count(['user_id' => $data['user_id']]) >= $rights['album_photo_pics']) {
            throw new Exception('您当前最多可上传'.$rights['album_photo_pics'].'张照片');
        }
        $data['status'] = MemberImages::STATUS_AUDITING;
        return parent::create($data);
    }

    public function delete(array $params)
    {
        $images = $this->getAll($params);
        $res = parent::delete($params);
        if($res) {
            $fileLogic = $this->getFileLogic();
            foreach ($images as $image) {
                $fileLogic->delete($image['file_id']);
            }
        }
        return $res;
    }

    public function getAll(array $params = null)
    {
        $res = parent::getAll($params);
        $dataList = [];
        if($res) {
            $fileIds = [];
            foreach ($res as $rs) {
                $fileIds[] = $rs['file_id'];
            }
            $files = $this->getFileLogic()->batchInfo($fileIds);
            if(!empty($files)) {
                foreach ($res as $rs) {
                    foreach ($files as $file) {
                        if($file['id'] == $rs['file_id']) {
                            $rs['url'] = $file['url'];
                            $dataList[] = $rs;
                            break;
                        }
                    }
                }
            }
        }
        return $dataList;
    }

    public function getAllByUserId($userId)
    {
        $res = $this->getAll([
            'user_id' => $userId,
            'status' => MemberImages::STATUS_APPROVED
        ]);
        return $res;
    }
}